import React, { useEffect } from 'react';
import { Form, Input, Select, InputNumber, Button, Space, message } from 'antd';
import { useDispatch, useSelector } from 'react-redux';
import { createDevice, updateDevice, clearError } from '../redux/features/deviceSlice';
import { validatePhone } from '../utils/tools';

const { Option } = Select;
const { TextArea } = Input;

const DeviceForm = ({ device = null, onSuccess, onCancel }) => {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const { isLoading, error } = useSelector((state) => state.device);

  // 设备类型选项
  const deviceTypes = [
    '服务器', '网络设备', '存储设备', '安全设备',
    '终端设备', '办公设备', '生产设备', '其他设备'
  ];

  // 当设备信息变化时，更新表单数据
  useEffect(() => {
    if (device) {
      form.setFieldsValue({
        deviceName: device.deviceName || '',
        deviceCode: device.deviceCode || '',
        deviceType: device.deviceType || '',
        description: device.description || ''
      });
    } else {
      form.resetFields();
    }
  }, [device, form]);

  // 处理表单提交
  const handleSubmit = async (values) => {
    try {
      // 创建设备数据对象，排除undefined的值
      const deviceData = {
        deviceName: values.deviceName,
        deviceCode: values.deviceCode,
        deviceType: values.deviceType,
        description: values.description || ''
      };

      if (device) {
        // 更新设备
        await dispatch(updateDevice({ id: device.id, deviceData })).unwrap();
        message.success('设备信息更新成功');
      } else {
        // 创建设备
        await dispatch(createDevice(deviceData)).unwrap();
        message.success('设备创建成功');
        form.resetFields();
      }

      // 调用成功回调
      if (onSuccess) {
        onSuccess();
      }
    } catch (error) {
      console.error('操作失败:', error);
      message.error(error?.message || '操作失败，请稍后再试');
    }
  };

  // 清除错误信息
  useEffect(() => {
    if (error) {
      const timer = setTimeout(() => {
        dispatch(clearError());
      }, 3000);
      return () => clearTimeout(timer);
    }
  }, [error, dispatch]);

  // 验证设备编号唯一性（模拟）
  const validateDeviceCode = async (rule, value) => {
    if (!value) {
      return Promise.reject('请输入设备编号');
    }
    // 实际项目中应该调用API验证编号唯一性
    // 这里仅做简单的模拟验证
    if (device && device.deviceCode === value) {
      return Promise.resolve();
    }
    // 假设设备编号不能包含特殊字符
    const codeRegex = /^[a-zA-Z0-9_-]+$/;
    if (!codeRegex.test(value)) {
      return Promise.reject('设备编号只能包含字母、数字、下划线和连字符');
    }
    return Promise.resolve();
  };

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      className="device-form"
    >
      <Form.Item
        label="设备名称"
      name="deviceName"
      rules={[
        { required: true, message: '请输入设备名称' },
        { max: 100, message: '设备名称不能超过100个字符' }
      ]}
      >
        <Input placeholder="请输入设备名称" />
      </Form.Item>

      <Form.Item
        label="设备类型"
      name="deviceType"
      rules={[
        { required: true, message: '请选择设备类型' }
      ]}
      >
        <Select placeholder="请选择设备类型">
          {deviceTypes.map((type) => (
            <Option key={type} value={type}>{type}</Option>
          ))}
        </Select>
      </Form.Item>

      <Form.Item
        label="设备编号"
      name="deviceCode"
      rules={[
        { required: true, message: '请输入设备编号' },
        { validator: validateDeviceCode }
      ]}
      >
        <Input placeholder="请输入设备编号（唯一标识）" />
      </Form.Item>

      <Form.Item
        label="设备描述"
        name="description"
        rules={[
          { max: 500, message: '设备描述不能超过500个字符' }
        ]}
      >
        <TextArea rows={4} placeholder="请输入设备描述（可选）" />
      </Form.Item>

      <Form.Item>
        <Space size="middle" style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <Button onClick={onCancel} disabled={isLoading}>
            取消
          </Button>
          <Button type="primary" htmlType="submit" loading={isLoading}>
            {device ? '更新' : '创建'}
          </Button>
        </Space>
      </Form.Item>

      {error && (
        <div className="error-message">
          {error}
        </div>
      )}
    </Form>
  );
};

export default DeviceForm;